<template>
  <div class="resume-submissions">
    <div class="toolbar">
      <el-input
        v-model="email"
        placeholder="按邮箱搜索，例如 user@example.com"
        clearable
        class="search-input"
        @keyup.enter="fetchList"
      />
      <el-button type="primary" :loading="loading" :disabled="!email" @click="fetchList">搜索</el-button>
      <el-button :loading="loading" @click="reset">重置</el-button>
    </div>

    <el-table v-loading="loading" :data="rows" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="email" label="邮箱" min-width="220" show-overflow-tooltip />
      <el-table-column prop="username" label="用户名" min-width="160" />
      <el-table-column prop="fileName" label="文件名" min-width="260" show-overflow-tooltip />
      <el-table-column prop="submittedAt" label="提交时间" min-width="200">
        <template #default="{ row }">{{ formatDate(row.submittedAt) }}</template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <template v-if="!isRowDownloading(row.id)">
            <el-button link type="primary" @click="onDownload(row)">下载</el-button>
          </template>
          <template v-else>
            <el-button link type="warning" @click="counselorStore.togglePauseDownload()">{{ isPaused ? '继续' : '暂停' }}</el-button>
            <el-button link type="danger" @click="counselorStore.cancelDownload()">取消</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <div v-if="downloading" class="download-progress">
      <el-progress :percentage="downloadProgress" :stroke-width="8" />
      <small>
        {{ downloadedBytes }} / {{ totalBytes }} bytes
        <span v-if="isPaused">（已暂停）</span>
      </small>
    </div>

    <div class="pager" v-if="total > pageSize">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="page"
        @current-change="(p:number)=>{ page=p; fetchList() }"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { getResumesByEmail } from '@/api/counselor/counselor'
import { useCounselorStore } from '@/stores/counselor/counselor'
import { storeToRefs } from 'pinia'

const email = ref('')
const loading = ref(false)
const rows = ref<any[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = 10

const counselorStore = useCounselorStore()
const { downloading, downloadProgress, isPaused, activeDownloadId, downloadedBytes, totalBytes } = storeToRefs(counselorStore)

function isRowDownloading(id: string | number) {
  return downloading.value && String(activeDownloadId.value) === String(id)
}

function formatDate(v?: string | number | Date | null) {
  if (!v) return '—'
  const d = typeof v === 'string' || typeof v === 'number' ? new Date(v) : v
  if (Number.isNaN(+d)) return '—'
  return new Date(d).toLocaleString()
}

async function fetchList() {
  if (!email.value || !email.value.trim()) {
    ElMessage.warning('请输入邮箱再搜索')
    return
  }
  loading.value = true
  try {
    // console.log('Fetching resumes for email:', email.value)
    const res = await getResumesByEmail({ email: email.value.trim(), page: page.value, size: pageSize })
    const data: any = res?.data ?? res
    rows.value = Array.isArray(data?.list) ? data.list : (Array.isArray(data) ? data : [])
    total.value = Number(data?.total ?? rows.value.length)
  } catch (e: any) {
    ElMessage.error(e?.message || '获取列表失败')
  } finally {
    loading.value = false
  }
}

function reset() {
  email.value = ''
  page.value = 1
  rows.value = []
  total.value = 0
}

async function onDownload(row: any) {
  try {
    await counselorStore.downloadFileInChunks(String(row.id), row.fileName)
  } catch (e: any) {
    ElMessage.error(e?.message || '下载失败')
  }
}
</script>

<style scoped>
.resume-submissions { min-width: 1000px; }
.toolbar {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 12px;
}
.search-input { flex: 1; }
.pager { margin-top: 12px; text-align: right; }
.download-progress { margin: 12px 0; }
</style>
